package com.example.workermanage

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.work.*
import kotlinx.android.synthetic.main.activity_main.*

const val INPUT_DATA_KEY = "input_data_key";
const val OUTPUT_DATA_KEY = "output_data_key";
const val WORK_A_NAME = "work a";
const val WORK_B_NAME = "work b";
const val SHARED_PREFERENCE_NAME = "shp_name";

class MainActivity : AppCompatActivity(),SharedPreferences.OnSharedPreferenceChangeListener {
    private val workerManager = WorkManager.getInstance(this)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //注册更新监听事件
        var sp:SharedPreferences =getSharedPreferences(SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE)
        sp.registerOnSharedPreferenceChangeListener(this)
        updateView()

        button.setOnClickListener {
            val workRequestA = createWork(WORK_A_NAME);
            val workRequestB = createWork(WORK_B_NAME);

            workerManager.beginWith(workRequestA).then(workRequestB).enqueue()

//            workerManager.enqueue(workRequest)
//            workerManager.getWorkInfoByIdLiveData(workRequest.id).observe(this, Observer {
//                Log.d("TAG", "onCreate: $it.state")
//                if(it.state== WorkInfo.State.SUCCEEDED){
//                    Log.d("TAG", "onCreate: ${it.outputData.getString(OUTPUT_DATA_KEY)}")
//                }
//            })
        }

    }

    private fun updateView(){
        val sp:SharedPreferences = getSharedPreferences(SHARED_PREFERENCE_NAME,Context.MODE_PRIVATE)
        textViewA.text =sp.getInt(WORK_A_NAME,0).toString()
        textViewB.text =sp.getInt(WORK_B_NAME,0).toString()
    }

    private fun createWork(name:String): OneTimeWorkRequest {
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

        //constraints 作为约束调节 有网络连接的时候才会执行
        return OneTimeWorkRequestBuilder<MyWorker>()
            .setConstraints(constraints)
            //为后台进程添加数据
            .setInputData(workDataOf(INPUT_DATA_KEY to name))
            .build()
    }

    //SharedPreferenceChanged 变化时
    override fun onSharedPreferenceChanged(p0: SharedPreferences?, p1: String?) {
        updateView()
    }
}